package com.yuhuofei2021.spring.boot.weather.service.implement;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.yuhuofei2021.spring.boot.weather.service.WeatherDataCollectionService;

/**
 * @description 天气数据采集子服务实现类
 * @author yuhuofei2021
 * @date 2021年10月3日
 */
@Service
public class WeatherDataCollectionServiceImplement implements WeatherDataCollectionService {

	public final static String MAIN = "http://wthrcdn.etouch.cn/weather_mini?";

	private final static Logger logger = LoggerFactory.getLogger(WeatherDataCollectionServiceImplement.class);

	// redis缓存数据过期超时时间
	private final static long Time_OUT = 1800L;

	@Resource
	private RestTemplate restTemplate;

	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public void syncDataByCityId(String cityId) {
		String url = MAIN + "citykey=" + cityId;
		this.saveWeatherData(url);
	}

	/**
	 * 
	 * @description 把天气数据写到缓存中
	 * @author yuhuofei2021
	 * @date 2021年9月21日
	 * @param urlString
	 */
	private void saveWeatherData(String urlString) {

		String repBody = null;
		ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();

		// 请求接口获取天气数据
		logger.info("请求外部天气查询接口==========");
		ResponseEntity<String> repString = restTemplate.getForEntity(urlString, String.class);

		if (200 == repString.getStatusCodeValue()) {
			repBody = repString.getBody();
			logger.info("外部天气查询接口返回结果：" + repBody);
		}

		// 将接口返回数据写入redis
		logger.info("将接口返回结果写入redis中！");
		ops.set(urlString, repBody, Time_OUT, TimeUnit.SECONDS);

	}

}
